import os
import requests
import profile
import helpers.FileHelper as FileHelper
import helpers.MiscHelper as MiscHelper
from package.Package import Package
from package.InfoSticker import InfoSticker
from package.MVViewer import MVViewer
from package.Transition import Transition


def cache_items(root_path):
    FileHelper.mkdir(root_path)
    for parent_path, dir_names, filenames in os.walk(root_path):
        if parent_path != root_path:
            continue
        items = [(int(dir_name[:2]), dir_name[3:]) for dir_name in dir_names]
        items.sort(key=lambda item: item[0])
        return items


def cache_print():
    print("##### package cache #####")
    items = cache_items(profile.effect_stack_root)
    for item in items:
        print("{:0>2}: {}".format(item[0], item[1]))


def cache_clear():
    FileHelper.rm_(profile.effect_stack_root)


def cache_push(name):
    items = cache_items(profile.effect_stack_root)
    item_name = "{:0>2}_{}".format(len(items), name)
    FileHelper.cp(profile.effect_workspace, (profile.effect_stack_root, item_name))
    return item_name


def cache_pop():
    items = cache_items(profile.effect_stack_root)
    count = len(items)
    if count > 0:
        last = items[count - 1]
        last_name = "{:0>2}_{}".format(last[0], last[1])
        FileHelper.prepare_dir(profile.effect_workspace, "*")
        FileHelper.cp_((profile.effect_stack_root, last_name), profile.effect_workspace)
        FileHelper.rm(profile.effect_stack_root, last_name)


def cache_swap(name):
    items = cache_items(profile.effect_stack_root)
    count = len(items)
    if count > 0:
        last_name = cache_push(name)
        prev = items[len(items) - 1]
        prev_name = "{:0>2}_{}".format(prev[0], prev[1])
        item_name = "{:0>2}_{}".format(prev[0], name)
        FileHelper.prepare_dir(profile.effect_workspace, "*")
        FileHelper.cp_((profile.effect_stack_root, prev_name), profile.effect_workspace)
        FileHelper.rm(profile.effect_stack_root, prev_name)
        FileHelper.mv((profile.effect_stack_root, last_name), (profile.effect_stack_root, item_name))


def upload_package(index):
    src = profile.effect_workspace
    dst = profile.effect_upload_target[index]
    tmp = FileHelper.solve_path(profile.effect_temporary, "upload.zip")
    FileHelper.zip(src, tmp)
    url = "http://{}/upload".format(dst)
    headers = {
        "Accept-Encoding": "gzip, deflate",
        "MIME-Version": "1.0",
        "Accept-Language": "zh-CN,en,*",
        "User-Agent": "Mozilla/5.0",
        "Host": dst,
    }
    files = {
        "files[]": ("upload.zip", open(tmp, "rb"), "zip")
    }
    print("Uploading: " + url)
    resp = requests.post(url, headers=headers, files=files)
    print(resp.text)
    FileHelper.rm(tmp)



def mv_render(capture):
    src = profile.effect_workspace
    dst = profile.mv_workspace
    cfg = FileHelper.r_json(src, "input/inputConfig.json")
    template_name = cfg["template"]
    FileHelper.rm(dst, "res/MV/templates", template_name)
    FileHelper.rm(dst, "res/MV/input")
    FileHelper.cp(src, (dst, "res/MV/templates", template_name))
    FileHelper.cp((src, "input"), (dst, "res/MV/input"))
    os.chdir(FileHelper.solve_path(dst, "libs"))

    os.system("./test_mv")
    if capture:
        idata = FileHelper.r_json(src, "data_test.json")
        odata = FileHelper.r_json(dst, "res/MV/input/inputConfig.json")
        odata["width"] = idata["w"]
        odata["height"] = idata["h"]
        FileHelper.w_json(odata, dst, "res/MV/input/inputConfig.json")
        os.system("./test_mv")

        video_path = FileHelper.solve_path(dst, "res/MV/result", template_name+".mp4")
        image_path = FileHelper.solve_path(dst, "res/MV/result", template_name+".jpg")
        os.system("ffmpeg -i {} -ss 0 -y -f image2 {}".format(video_path, image_path))


def cc_render():
    src = profile.effect_workspace
    dst = profile.cc_workspace
    FileHelper.rm(dst, "effects", "runtime")
    FileHelper.cp(src, (dst, "effects", "runtime"))


def parse(root_path):
    package_conf = FileHelper.r_json(root_path, "config.json")
    single_amaz = MiscHelper.json_get(package_conf, "effect", "AmazingScene")
    if single_amaz is not None:
        return Package(root_path, package_conf)

    feature_list = MiscHelper.json_get(package_conf, "effect", "Link")
    if len(feature_list) == 0:
        return Package(root_path, package_conf)

    package_type = MiscHelper.json_get(feature_list, 0, "type")
    if package_type is None:
        return None
    elif package_type == "InfoSticker":
        return InfoSticker(root_path, package_conf)
    elif package_type == "MV":
        return MVViewer(root_path, package_conf)

    if FileHelper.exists(root_path, "extra.json"):
        extra_conf = FileHelper.r_json(root_path, "extra.json")
        if "transition" in extra_conf:
            return Transition(root_path, package_conf)

    return Package(root_path, package_conf)




